/*
 * @(#)org.example.netty.heartbeat 2020/4/2/0002
 *
 * Copy Right@ 人人译视界
 */


package org.example.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.example.netty.heartbeat.MyServerHandler;

import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/2/0002
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class MyServer {
	public static void main(String[] args) throws InterruptedException {
		NioEventLoopGroup boss = new NioEventLoopGroup(1);
		NioEventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, worker)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))// 日志处理器
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline pipeline = socketChannel.pipeline();
							// 因为使用http协议，因此需要使用http的编解码器
							pipeline.addLast(new HttpServerCodec());
							// 是以块方式写，添加ChunkedWriteHandler处理器
							pipeline.addLast(new ChunkedWriteHandler());
							/**
							 * 因为http在传输过程中是分段的，HttpObjectAggregator可以将多个段聚合起来
							 * 这就是为什么当浏览器发送大量数据时，就会发出多次http请求
							 */
							pipeline.addLast(new HttpObjectAggregator(8192));
							/**
							 * 对于WebSocket数据是以帧的形式传输的
							 * 可以看到websocketFrame下面有6个子类
							 * 浏览器请求时：ws://localhost:8080/xxx
							 * 将http协议升级为ws协议
							 */
							pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
							pipeline.addLast(new MyTextWebsocketFrameHandler());
						}
					});
			System.out.println("netty服务器启动");
			ChannelFuture sync = bootstrap.bind(8080).sync();
			sync.channel().closeFuture().sync();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
